import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/song.dart';

class CustomPlaylistService {
  static const String _playlistKey = 'custom_playlist';

  static final List<VoidCallback> _listeners = [];

  static void addListener(VoidCallback listener) {
    _listeners.add(listener);
  }

  static void removeListener(VoidCallback listener) {
    _listeners.remove(listener);
  }

  static void _notifyListeners() {
    for (final l in _listeners) {
      l();
    }
  }

  static Future<List<Song>> getPlaylist() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final list = prefs.getStringList(_playlistKey) ?? [];
      return list.map((j) => Song.fromJson(jsonDecode(j))).toList();
    } catch (e) {
      print('Error getting custom playlist: $e');
      return [];
    }
  }

  static Future<void> addSong(Song song) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final list = prefs.getStringList(_playlistKey) ?? [];
      var songs = list.map((j) => Song.fromJson(jsonDecode(j))).toList();
      // 避免重复
      final exists = songs.any((s) => s.effectiveId == song.effectiveId && s.source == song.source);
      if (!exists) {
        songs.insert(0, song);
        final updated = songs.map((s) => jsonEncode(s.toJson())).toList();
        await prefs.setStringList(_playlistKey, updated);
        _notifyListeners();
      }
    } catch (e) {
      print('Error adding to custom playlist: $e');
    }
  }

  static Future<void> removeSong(Song song) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final list = prefs.getStringList(_playlistKey) ?? [];
      var songs = list.map((j) => Song.fromJson(jsonDecode(j))).toList();
      songs.removeWhere((s) => s.effectiveId == song.effectiveId && s.source == song.source);
      final updated = songs.map((s) => jsonEncode(s.toJson())).toList();
      await prefs.setStringList(_playlistKey, updated);
      _notifyListeners();
    } catch (e) {
      print('Error removing from custom playlist: $e');
    }
  }

  static Future<void> clearPlaylist() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(_playlistKey);
      _notifyListeners();
    } catch (e) {
      print('Error clearing custom playlist: $e');
    }
  }

  // ===== 导入 / 导出 =====
  static String _defaultPath({String fileName = 'ly_music_custom_playlist.json'}) {
    final home = Platform.environment['USERPROFILE'] ?? Platform.environment['HOME'] ?? '.';
    final downloads = Platform.isWindows ? 'Downloads' : 'Downloads';
    return '$home/$downloads/$fileName';
  }

  static Future<String?> exportToFile({String? filePath}) async {
    try {
      final songs = await getPlaylist();
      final jsonStr = jsonEncode(songs.map((s) => s.toJson()).toList());
      final path = filePath ?? _defaultPath();
      final file = File(path);
      await file.writeAsString(jsonStr);
      return path;
    } catch (e) {
      print('Error exporting custom playlist: $e');
      return null;
    }
  }

  static Future<int> importFromFile({String? filePath}) async {
    try {
      final path = filePath ?? _defaultPath();
      final file = File(path);
      if (!await file.exists()) return 0;
      final content = await file.readAsString();
      final List<dynamic> arr = jsonDecode(content);
      final importedSongs = arr.map((j) => Song.fromJson(j)).toList();

      // 加载现有自定义歌单
      final prefs = await SharedPreferences.getInstance();
      final existingJson = prefs.getStringList(_playlistKey) ?? [];
      final existing = existingJson.map((json) => Song.fromJson(jsonDecode(json))).toList();

      // 将导入的歌曲按 key 映射，便于覆盖与去重
      String keyOf(Song s) => '${s.source}::${s.effectiveId}';
      final Map<String, Song> importedByKey = {
        for (final s in importedSongs) keyOf(s): s,
      };

      final Set<String> existingKeys = existing.map(keyOf).toSet();

      // 覆盖：用导入版本替换现有同 key 歌曲
      for (int i = 0; i < existing.length; i++) {
        final k = keyOf(existing[i]);
        final imported = importedByKey[k];
        if (imported != null) {
          existing[i] = imported;
          importedByKey.remove(k);
        }
      }

      // 追加：将剩余导入歌曲（现有列表中不存在）附加到末尾
      for (final entry in importedByKey.entries) {
        if (!existingKeys.contains(entry.key)) {
          existing.add(entry.value);
        }
      }

      // 保存与通知
      final updatedJson = existing.map((s) => jsonEncode(s.toJson())).toList();
      await prefs.setStringList(_playlistKey, updatedJson);
      _notifyListeners();
      return importedSongs.length;
    } catch (e) {
      print('Error importing custom playlist: $e');
      return 0;
    }
  }
}